package com.blb.community.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blb.community.Annotation.Log;
import com.blb.community.entity.SysUser;
import com.blb.community.entity.vo.SysUserVO;
import com.blb.community.service.ISysUserService;
import com.blb.community.utils.EasyExcelUtil;
import com.blb.community.utils.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author 帅帅
 * @since 2022-07-02
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/sys-user")
public class SysUserController {
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @ApiOperation("修改密码")
    @PutMapping("/chonzhi/{id}")
    public ResponseResult<String> chongZhi(@PathVariable Integer id) {
        String encode = bCryptPasswordEncoder.encode("123");
        SysUser sysUser = new SysUser();
        sysUser.setUserId(id);
        sysUser.setPassword(encode);
        boolean b = sysUserService.updateById(sysUser);
        if (b) {
            return ResponseResult.ok("重置密码成功");
        }
        return ResponseResult.error("重置密码失败");
    }

    @Log(module = "添加用户", operationType = 1, requestMethod = "POST")
    @ApiOperation("添加用户")
    @PostMapping("/addUser")
    public ResponseResult<String> addUser(@RequestBody SysUserVO sysUserVO) {
        sysUserVO.setPassword(bCryptPasswordEncoder.encode("123"));
        sysUserVO.setAvatar("http://121.41.82.94/group1/M00/00/00/rBo7GGLfN7qAZl6IAABIjbF3INM096.jpg");
        sysUserService.addUser(sysUserVO);
        return ResponseResult.ok("添加成功");
    }


    @ApiOperation("excel的导出")
    @PostMapping("/excel")
    public void downloadExcel(@RequestBody List<SysUser> list, HttpServletResponse response) {
        EasyExcelUtil.write(list, SysUserVO.class, response);
    }


    @ApiOperation("excel导入")
    @PostMapping("/readExcel")
    public void readExcel(MultipartFile file) throws IOException {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            EasyExcelUtil.reade(inputStream, SysUser.class, sysUserService);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            inputStream.close();
        }

    }

    @ApiOperation(value = "模糊查询")
    @PostMapping("/list")
    public ResponseResult<IPage<List<SysUserVO>>> list(@RequestBody SysUserVO sysUserVO) {
        IPage<List<SysUserVO>> iPage = sysUserService.getUserLimitList(sysUserVO);
        return ResponseResult.ok(iPage);
    }

    @GetMapping
    @ApiOperation(value = "查询所有用户")
    public ResponseResult<List<SysUserVO>> getAlluser() {
        List<SysUserVO> list = sysUserService.getUserlist();
        return ResponseResult.ok(list);
    }

    @ApiOperation(value = "根据用户名查询用户")
    @GetMapping("{username}")
    public ResponseResult<SysUser> queryUserByName(@PathVariable String username) {
        SysUser one = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserName, username));
        return ResponseResult.ok(one);

    }


    @ApiOperation("修改用户信息")
    @PutMapping("/updateUserInfo")
    public ResponseResult<String> updateUserInfo(@RequestBody SysUserVO userVO) {
        sysUserService.updateUserInfo(userVO);

        return ResponseResult.ok("修改成功");
    }

    @ApiOperation("根据id删除")
    @PutMapping("/{id}")
    @Log(module = "根据id删除", operationType = 3, requestMethod = "DELETE")
    public ResponseResult<String> deleteUserId(@PathVariable Integer id) {
        boolean b = sysUserService.removeById(id);
        if (b) {
            return ResponseResult.ok("ok");
        }
        return ResponseResult.error("删除错误");
    }


    @ApiOperation("修改用户信息")
    @PutMapping
    @Log(module = "修改用户信息", operationType = 2, requestMethod = "PUT")
    public ResponseResult<String> putUserInfo(@RequestBody SysUser user) {
        boolean update = sysUserService.update(user, new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserName, user.getUserName()));
        if (update) {
            return ResponseResult.ok("ok");
        }
        return ResponseResult.error("修改错误");
    }

    @ApiOperation("修改用户密码")
    @PutMapping("/userInfo")
    @Log(module = "修改用户密码", operationType = 2, requestMethod = "PUT")
    public ResponseResult<String> putUser(@RequestBody SysUser user) {
        if (user.getPassword() != null) {
            String encode = bCryptPasswordEncoder.encode(user.getPassword());
            user.setPassword(encode);
        }
        SysUser one = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserName, user.getUserName()));
        user.setUserId(one.getUserId());
        boolean update = sysUserService.update(user, new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserId, user.getUserId()));
        if (update) {
            return ResponseResult.ok("ok");
        }
        return ResponseResult.error("修改错误");
    }

    @ApiOperation("查看用户密码状态")
    @PostMapping("/getPassStatu")
    public ResponseResult<String> getPassStatu(@RequestBody String oldPass) {
        SysUser one = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserName, SecurityContextHolder.getContext().getAuthentication().getName()));
        String substring = oldPass.substring(0, oldPass.lastIndexOf("="));
        boolean matches = bCryptPasswordEncoder.matches(substring, one.getPassword());
        if (matches) {
            return ResponseResult.ok("ok");
        }
        return ResponseResult.error("密码错误");
    }

    @ApiOperation("获取用户是否重复")
    @GetMapping("getUserNameCount/{userName}")
    public ResponseResult<String> getUserNameCount(@PathVariable String userName) {
        SysUser one = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserName, userName).eq(SysUser::getDelFlag,0));
        if (null == one) {
            return ResponseResult.ok("用户正确");
        } else {
            return ResponseResult.error("用户名重复");
        }
    }
}
